import { getDepartments } from '@/api/dist'
import { getDictList } from '@/api/dict'
import { treeReplaceKeys } from '@/utils/util'

const app = {
  state: {
    dict: {}
  },
  mutations: {
    SET_DICT: (state, obj) => {
      state.dict = {
        ...state.dict,
        ...obj
      }
    }
  },
  actions: {
    // 获取设备类型
    getDict ({ commit }, appFieldObj) {
      let fn
      const params = {}
      let fieldLabel = 'dicName'
      let fieldValue = 'dicCode'
      return new Promise(resolve => {
        let appFieldName = ''
        if (appFieldObj && typeof appFieldObj !== 'string') {
          appFieldName = appFieldObj.type
        } else {
          appFieldName = appFieldObj
        }
        // 获取科室类别
        if (appFieldName === 'departs') {
          fn = getDepartments
          fieldLabel = 'name'
          fieldValue = 'orgId'
        } else {
          fn = getDictList
          params.dicTypeCode = appFieldName
        }
        fn(params).then(res => {
          const listTemp = res.data
          const list = treeReplaceKeys(listTemp, { [fieldLabel]: 'label', [fieldValue]: 'value' })
          commit('SET_DICT', { [appFieldName]: list })
          resolve(list)
        })
      })
    }
  }
}

export default app
